package com.yqw.onlineDocs.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yqw.onlineDocs.annotation.AuthCheck;
import com.yqw.onlineDocs.common.BaseResponse;
import com.yqw.onlineDocs.common.DeleteRequest;
import com.yqw.onlineDocs.common.ErrorCode;
import com.yqw.onlineDocs.common.ResultUtils;
import com.yqw.onlineDocs.constant.UserConstant;
import com.yqw.onlineDocs.exception.BusinessException;
import com.yqw.onlineDocs.exception.ThrowUtils;
import com.yqw.onlineDocs.model.dto.documentTemplate.DocumentTemplateAddRequest;
import com.yqw.onlineDocs.model.dto.documentTemplate.DocumentTemplateEditRequest;
import com.yqw.onlineDocs.model.dto.documentTemplate.DocumentTemplateQueryRequest;
import com.yqw.onlineDocs.model.dto.documentTemplate.DocumentTemplateUpdateRequest;
import com.yqw.onlineDocs.model.entity.DocumentTemplate;
import com.yqw.onlineDocs.model.entity.User;
import com.yqw.onlineDocs.model.vo.DocumentTemplateVO;
import com.yqw.onlineDocs.service.DocumentTemplateService;
import com.yqw.onlineDocs.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 文档模板接口
 */
@RestController
@RequestMapping("/documentTemplate")
@Slf4j
public class DocumentTemplateController {

    @Resource
    private DocumentTemplateService documentTemplateService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建文档模板
     *
     * @param documentTemplateAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addDocumentTemplate(@RequestBody DocumentTemplateAddRequest documentTemplateAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(documentTemplateAddRequest == null, ErrorCode.PARAMS_ERROR);
        // todo 在此处将实体类和 DTO 进行转换
        DocumentTemplate documentTemplate = new DocumentTemplate();
        BeanUtils.copyProperties(documentTemplateAddRequest, documentTemplate);
        // 数据校验
        documentTemplateService.validDocumentTemplate(documentTemplate, true);
        // todo 填充默认值
        User loginUser = userService.getLoginUser(request);
        documentTemplate.setUserId(loginUser.getId());
        // 写入数据库
        boolean result = documentTemplateService.save(documentTemplate);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newDocumentTemplateId = documentTemplate.getId();
        return ResultUtils.success(newDocumentTemplateId);
    }

    /**
     * 删除文档模板
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteDocumentTemplate(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        DocumentTemplate oldDocumentTemplate = documentTemplateService.getById(id);
        ThrowUtils.throwIf(oldDocumentTemplate == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldDocumentTemplate.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = documentTemplateService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新文档模板（仅管理员可用）
     *
     * @param documentTemplateUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateDocumentTemplate(@RequestBody DocumentTemplateUpdateRequest documentTemplateUpdateRequest) {
        if (documentTemplateUpdateRequest == null || documentTemplateUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        DocumentTemplate documentTemplate = new DocumentTemplate();
        BeanUtils.copyProperties(documentTemplateUpdateRequest, documentTemplate);
        // 数据校验
        documentTemplateService.validDocumentTemplate(documentTemplate, false);
        // 判断是否存在
        long id = documentTemplateUpdateRequest.getId();
        DocumentTemplate oldDocumentTemplate = documentTemplateService.getById(id);
        ThrowUtils.throwIf(oldDocumentTemplate == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = documentTemplateService.updateById(documentTemplate);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取文档模板（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<DocumentTemplateVO> getDocumentTemplateVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        DocumentTemplate documentTemplate = documentTemplateService.getById(id);
        ThrowUtils.throwIf(documentTemplate == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(documentTemplateService.getDocumentTemplateVO(documentTemplate, request));
    }

    /**
     * 分页获取文档模板列表（仅管理员可用）
     *
     * @param documentTemplateQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<DocumentTemplate>> listDocumentTemplateByPage(@RequestBody DocumentTemplateQueryRequest documentTemplateQueryRequest) {
        long current = documentTemplateQueryRequest.getCurrent();
        long size = documentTemplateQueryRequest.getPageSize();
        // 查询数据库
        Page<DocumentTemplate> documentTemplatePage = documentTemplateService.page(new Page<>(current, size),
                documentTemplateService.getQueryWrapper(documentTemplateQueryRequest));
        return ResultUtils.success(documentTemplatePage);
    }

    /**
     * 分页获取文档模板列表（封装类）
     *
     * @param documentTemplateQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<DocumentTemplateVO>> listDocumentTemplateVOByPage(@RequestBody DocumentTemplateQueryRequest documentTemplateQueryRequest,
                                                                               HttpServletRequest request) {
        long current = documentTemplateQueryRequest.getCurrent();
        long size = documentTemplateQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 30, ErrorCode.PARAMS_ERROR, "爬虫限制，每页最多只能获取 30 条数据");
        // 查询数据库
        Page<DocumentTemplate> documentTemplatePage = documentTemplateService.page(new Page<>(current, size),
                documentTemplateService.getQueryWrapper(documentTemplateQueryRequest));
        // 获取封装类
        return ResultUtils.success(documentTemplateService.getDocumentTemplateVOPage(documentTemplatePage, request));
    }

    /**
     * 分页获取当前登录用户创建的文档模板列表
     *
     * @param documentTemplateQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<DocumentTemplateVO>> listMyDocumentTemplateVOByPage(@RequestBody DocumentTemplateQueryRequest documentTemplateQueryRequest,
                                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(documentTemplateQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        documentTemplateQueryRequest.setUserId(loginUser.getId());
        long current = documentTemplateQueryRequest.getCurrent();
        long size = documentTemplateQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<DocumentTemplate> documentTemplatePage = documentTemplateService.page(new Page<>(current, size),
                documentTemplateService.getQueryWrapper(documentTemplateQueryRequest));
        // 获取封装类
        return ResultUtils.success(documentTemplateService.getDocumentTemplateVOPage(documentTemplatePage, request));
    }

    /**
     * 编辑文档模板（给用户使用）
     *
     * @param documentTemplateEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editDocumentTemplate(@RequestBody DocumentTemplateEditRequest documentTemplateEditRequest, HttpServletRequest request) {
        if (documentTemplateEditRequest == null || documentTemplateEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        DocumentTemplate documentTemplate = new DocumentTemplate();
        BeanUtils.copyProperties(documentTemplateEditRequest, documentTemplate);
        // 数据校验
        documentTemplateService.validDocumentTemplate(documentTemplate, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = documentTemplateEditRequest.getId();
        DocumentTemplate oldDocumentTemplate = documentTemplateService.getById(id);
        ThrowUtils.throwIf(oldDocumentTemplate == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldDocumentTemplate.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = documentTemplateService.updateById(documentTemplate);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    // endregion
}
